﻿using Geek.Server.Core.Serialize;
using NLog;

namespace Geek.Server.Core.Net.Http
{
    public abstract class BaseHttpHandler
    {
        public abstract Task<HttpResponse> Action(string ip, string requestBody);
    }

    public abstract class BaseHttpHandler<TReq> : BaseHttpHandler where TReq : HttpRequest, new()
    {
        protected static readonly Logger LOGGER = LogManager.GetCurrentClassLogger();
        
        public override async Task<HttpResponse> Action(string ip, string requestBody)
        {
            TReq req;

            try
            {
                req = requestBody.FromJsonStr<TReq>();
                if (req == null)
                    return HttpResponse.Create(1000003); // 参数错误
            }
            catch (Exception)
            {
                return HttpResponse.Create(1000003); // 参数错误
            }

            try
            {
                return await Execute(ip, req);
            }
            catch (Exception e)
            {
                LOGGER.Error(e);
                return HttpResponse.Create(1000002); // 内部错误
            }
        }

        protected abstract Task<HttpResponse> Execute(string ip,  TReq req);
    }
}